package com.speciality.demo.demos.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 放行：登录页、API 接口、静态资源
        if (requestURI.endsWith("login.html")
                || requestURI.startsWith("/api/")
                || requestURI.startsWith("/static/")) {
            return true;
        }

        // 校验会话：存在则放行，否则跳转到登录页
        HttpSession session = request.getSession();
        if (session.getAttribute("user") != null) {
            return true;
        } else {
            response.sendRedirect("/login.html"); // 强制跳转登录
            return false;
        }
    }
}
